package basic

import (
	"chat/app"
	"chat/app/common"
	"chat/app/dao"
	"chat/utils"
	"context"
	"fmt"
	"github.com/go-playground/validator/v10"
	"log"
	"strings"
)

// 用户登录验证
type userAuth struct {
	Mobile string `from:"mobile" validate:"required,min=11,max=20"`
	Passwd string `from:"passwd" validate:"required,min=6,max=25"`
}

// LoginAuthService 用户登陆
func LoginAuthService(ctx context.Context, c *app.Context) any {

	// 创建返回信息
	data := make(map[string]interface{})
	code := common.INVALID_PARAMS

	mobile := c.PostForm("mobile")
	passwd := c.PostForm("passwd")

	// 验证参数
	valid := validator.New()
	a := userAuth{
		Mobile: mobile,
		Passwd: passwd,
	}
	ok := valid.Struct(a)
	if ok != nil {
		// 翻译成中文
		trans := utils.ValidateTransInit(valid)
		verrs := ok.(validator.ValidationErrors)
		errs := make(map[string]string)
		for key, value := range verrs.Translate(trans) {
			errs[key[strings.Index(key, ".")+1:]] = value
		}
		fmt.Println(errs)
		//fmt.Printf("Err(s):\n%+v\n", ok)
		return common.Response(code, common.GetMsg(code), data)
	}

	// 验证用户
	user, isExist := dao.UserGetOneNamePass(mobile, 1)
	log.Printf("user: %#v,isExist: %#v ", user, isExist)
	if isExist {
		if utils.ValidatePasswd(passwd, user.Salt, user.Passwd) {
			token, err := utils.GenerateToken(user.Id)
			if err != nil {
				code = common.ERROR_AUTH_TOKEN
			} else {
				data["token"] = token
				data["id"] = user.Id
				data["sex"] = user.Sex
				data["avatar"] = user.Avatar
				data["nickname"] = user.Nickname
				data["memo"] = user.Memo
				code = common.SUCCESS
				// 保存token
				token = utils.MD5Encode(token)
				dao.UserUpdateToken(user.Id, token)
			}
		} else {
			code = common.ERROR_AUTH
		}
	} else {
		code = common.ERROR_AUTH
	}

	return common.Response(code, common.GetMsg(code), data)
}

// LogoutService 用户退出
func LogoutService(ctx context.Context, c *app.Context) any {
	// 创建返回信息
	data := make(map[string]interface{})
	code := common.SUCCESS

	// 清除token 退出登录
	uidStr := c.UserInfo["uid"]
	uid := uidStr.(int64)
	token := ""
	dao.UserUpdateToken(uid, token)

	return common.Response(code, common.GetMsg(code), data)
}
